package com.teensoft.base.startup;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.teensoft.base.exception.HandlerInvokeException;
import com.teensoft.base.exception.ServiceException;

public class StartUpServlet extends HttpServlet {

	private static final Log log = LogFactory.getLog(StartUpServlet.class);
	private static final long serialVersionUID = 8625528140666627913L;
	private static final String PARAM_HANDLER = "startup.handlers";
	
	IHandler[] handlers = null;
	
	public void init() throws ServletException {
		String str_handlers = getInitParameter(PARAM_HANDLER);
		initializeHandlers(str_handlers);
		initHandlers();
	}
	
	
	
	public void destroy() {
		destoryHandlers();
	}
	
	private void initHandlers(){
		for(IHandler handler : handlers)
			handlerInit(handler);
	}
	
	private void handlerInit(IHandler handler){
		try {
			handler.invokeInit(getServletContext());
		} 
		catch (Exception e) {
			log.warn("handler -> " + handler + " startup error. It not be used!", new HandlerInvokeException(e));
		}
	}
	
	private void destoryHandlers(){
		for(IHandler handler : handlers)
			handlerDestory(handler);
	}
	
	private void handlerDestory(IHandler handler){
		try {
			handler.invokeDestory(getServletContext());
		} 
		catch (Exception e) {
			log.warn("handler -> " + handler + " destory error. resource may not be released !", new HandlerInvokeException(e));
		}
	}
	
	private void initializeHandlers(String str_handlers){
		String[] hs = str_handlers.split(",");
		handlers = new IHandler[hs.length];
		int i = 0;
		for(String h : hs){
			try {
				handlers[i++] = (IHandler)Class.forName(h).newInstance();
			} 
			catch (InstantiationException e) {
				log.warn("", new ServiceException(e));
			} 
			catch (IllegalAccessException e) {
				log.warn("", new ServiceException(e));
			} 
			catch (ClassNotFoundException e) {
				log.warn("", new ServiceException(e));
			}
		}
	}
}
